define(function(require, exports, module) {
	'use strict';
    
    var rk = require('rk');
    require('../../su/xsySuRefer/widget');

    $.widget('rk.xsyOppContactRefer', $.rk.xsySuRefer, {
        options: {
            iconClass: 'xsy_su_refer_contact_icon',
            business: 'contact',
            createAct: 'addContact'
        },
        _create: function(){
            var me = this;
            var elem = me.element;
            var opt = me.options;

            elem.addClass('xsy_contact_refer');

            me._super();

            me._reload();

            me.bindEventHandler();
        },
        _reload:function(){
            var me = this;
            var elem = me.element;
            var opt = me.options;

            var fromBelongId = opt.parentEntityId;
            var fromDataId = me._getDetailId();
            var fromItemId = opt.referItemId;

            me._loadData({}, function (result){
                opt.data = result;
                var config = {
                    iconClass: opt.iconClass,
                    linkOfMore: '/contact.action?fromBelongId=' + fromBelongId + "&fromDataId=" + fromDataId + "&fromItemId=" + fromItemId,
                    linkOfFinal: '/final/contact.action?id={{id}}',
                    buttons: ['create'],
                    children: [
                        {   
                            type: 'card'
                        },
                        {   
                            type: 'grid'
                        }
                    ],
                    cellMenu: false,
                    isFold: false,
                    itemRender : {
                        contactRoleId : function(rowData, cellData, itemType){

                            var roleTpl = 
                                '<div class="xsy_contact_refer_selectmunu">' + 
                                    '<div class="xsy_contact_refer_staselect" value="{{data.contactRoleId}}" contactId="{{data.id}}" oppcontactId="{{data.oppContactId}}">' +
                                        '<span>{{data.contactRoleName}}</span>' + 
                                        '<i class="arrow"></i>'
                                    '</div>'
                                '</div>';

                            if(rowData.contactRoleId == '-1'){
                                rowData.contactRoleName = "请选择角色";
                            }
                            var roleSelectHtml = rk.templateText(roleTpl, {data : rowData});
                            return roleSelectHtml;
                        },

                        contactName : function(rowData, cellData, itemType){
                            var contactNameTpl = '<a href="/final/contact.action?id={{data.id}}" target="_blank"><b class="xsy_contact_refer_name">{{data.contactName}}</b>{{if data.mainFlg == 1}}<span class="xsy_contact_refer_sta" title="主联系人"></span>{{/if}}</a>';
                            var contactNameHtml = rk.templateText(contactNameTpl, {data : rowData});

                            return contactNameHtml;
                        }
                    }
                };
                /*if(me.data_bound){
                    me.bindData(result.self);
                }else{
                    me._render(config, result);
                }*/
                me.processData(result);
                me._render(config, result);
            });
        },

        processData : function(result){
            var me = this;
            var elem = me.element;
            var opt = me.options;
            
            var self = result.self;
            if(!self){return;}
            var entityData = self.entityData;
            if(!entityData){return;}
            
            var contactRoles = self.contactRoles;
            var roleMap = {};
            var contactToOppContactMap = {};
            var contactIdToContact = {};

            me.roleMap = roleMap;
            me.contactToOppContactMap = contactToOppContactMap;
            me.contactRoles = contactRoles;
            me.entityData = entityData;
            me.contactIdToContact = contactIdToContact;

            contactRoles.forEach(function(item, index){
                roleMap[item.id] = item;
            })


            entityData.forEach(function(item, index){
                contactToOppContactMap[item.id] = item.oppContactId;
                contactIdToContact[item.id] = item;
                var contactRoleId = item.contactRoleId;
                if(item.mainFlg){
                    me.mainContact = item;
                }
                
                if(contactRoleId){
                    var roles = contactRoleId.split(',');
                    var contactRoleName = roles.map(function(item, index){
                        return roleMap[item] ? roleMap[item].parameterName : "";
                    }).join(',');

                   item.contactRoleName = contactRoleName;;
                }else{
                    item.contactRoleId = '-1';
                }   
            })

            var maxGridColCount = opt.attributes.maxGridColCount ? opt.attributes.maxGridColCount : 6;
            result.self.itemList = result.self.itemList.slice(0, 6);
            opt.attributes.maxGridColCount = maxGridColCount + 1;


            appendContactRoleItemToItemList(result.self.itemList);
            function appendContactRoleItemToItemList(itemList){
                itemList.push({
                    name : 'contactRoleId',
                    label : '角色'

                })
            }
            
        },
        getCardTpl : function(){
            return require('./widget.tpl');
        },

        _setMain : function(info){
            var me = this;
            me.do_setMain(info, function(){
                me._reload();
                me._triggerOuterEvent('referDataUpdated');
            })
        },

        do_setMain : function(celldata, callback){
            var me = this;
            var elem = me.element;
            var opt = me.options;

            if(me.mainContact && me.mainContact.id == celldata.id){
                $.msg(celldata.name + rk.i18n('OPPORTUNITY_BELONG_TO_MAIN_CONTACT', SESSION.keywords.opportunity, SESSION.keywords.contact), true);
                return;
            }

            $.each(me.entityData, function(index, contact){
                if(contact.id == celldata.id){
                    me.newMainContact = contact;
                }
            });

            var tip = rk.i18n('OPPORTUNITY_SET_MAIN_CONTACT_CONFIRM', celldata.name, SESSION.keywords.contact, SESSION.keywords.opportunity) + (me.mainContact ? rk.i18n('OPPORTUNITY_SET_MAIN_CONTACT_CONFIRM_TIP', me.mainContact.contactName, SESSION.keywords.contact) : '');

            $.confirm(tip, function() {
                $.postJson('/json/crm_opportunity/set-main.action', {
                    oppContactId: me.newMainContact.oppContactId
                }).done(function(json) {
                    if (json.status == 0) {
                        $.msg(rk.i18n('CRM_CORE_SET') + rk.i18n('CRM_CORE_SUCCESS'), 1);
                        callback();
                    } else {
                        $.msg(rk.i18n('CRM_CORE_SET') + rk.i18n('CRM_CORE_FAILED'));
                    }
                }).fail(function(def, code, message) {
                    def.status != 0 && $.msg(rk.i18n('REQUEST_ERROR'));
                });
            });
            return false;
        },


        bindEventHandler : function(){
            var me = this;
            var elem = me.element;
            var opt = me.options;

            rk.delegateMenu({
                container: elem,
                buttonSel: 'div.xsy_contact_refer_staselect',
                menuHtml: '',
                itemSel: 'li',
                position:{
                    my: 'center top',
                    at: 'center-40 bottom+10'
                },
                onOpen: function(button, menuSel, menuPos) {

                    if(opt.data && opt.data.self && !opt.data.self.canChangeContactRole){
                        return false;
                    }  

                    //var contactRoleId = button.attr('value') ? button.attr('value').split(',') : [];
                    var contactId = button.attr('contactId');
                    //不从按钮上面获取，实时从数据中获取，保持列表状态和卡片状态数据统一
                    var contact = me.contactIdToContact[contactId];
                    var contactRoleId = contact.contactRoleId;
                    var oppContactId = button.attr('oppContactId');

                    var menuHtml = getMenuHtml(me.contactRoles, contactRoleId, contactId, oppContactId);
                    $(menuSel).html(menuHtml);
                },
                onSelect: function(e, button, itemEl) {
                    var $this = itemEl;
                    var $ul = $this.parent();
                    var contactId = $ul.attr('contactId');
                    if($this.hasClass('active')){
                        $this.removeClass('active');
                    }else{
                        $this.addClass('active');
                    }

                    var selectRoleId = new Array();
                    var selectRoleName = new Array();

                    $ul.find('li.active').each(function(i, item){
                        var $item = $(item);
                        selectRoleId.push($item.attr('roleId'));
                        selectRoleName.push($item.find('a').html());
                    })

                    $.postJson('/json/crm_opportunity/update-contact-role.action', {
                        //这里是个坑，参数名为oppContactId，值却是contactId,怎么做的接口
                        oppContactId: contactId,
                        contactRoleId: selectRoleId.toString(),
                        opportunityId: me._getDetailId()
                    }).done(function(json) {
                        button.attr('value', selectRoleId.toString());
                        
                        selectRoleName = selectRoleName.length < 1  ? "请选择角色" : selectRoleName.toString();

                        button.find('span').html(selectRoleName);
                        button.attr('title', selectRoleName);
                        me.contactIdToContact[contactId].contactRoleId = selectRoleId.toString();
                        me.contactIdToContact[contactId].contactRoleName = selectRoleName;

                        $.msg(rk.i18n('CRM_CORE_MODIFY') + rk.i18n('CRM_CORE_SUCCESS'), 1);
                    });
                    
                }
            });

            var tpl = require('./menu.tpl');
            function getMenuHtml(allRole, contactRole, contactId, oppContactId){

                allRole.forEach(function(item, i){
                    (contactRole.indexOf(item.id+'') >= 0) && (item.check = true) || (item.check = false);
                })

                var menuHtml = rk.templateText(tpl, {allRole : allRole, contactRole : contactRole, contactId : contactId, oppContactId : oppContactId});
                return menuHtml;
            }

        },

    });
});